package com.gyj.util;

import java.awt.Font;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.imageio.ImageIO;

import org.apache.commons.lang.time.DateFormatUtils;
import org.apache.poi.ss.usermodel.Drawing;
import org.apache.poi.xssf.streaming.SXSSFSheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFClientAnchor;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.CategoryAxis;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.axis.NumberTickUnit;
import org.jfree.chart.labels.StandardCategoryItemLabelGenerator;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.renderer.category.BarRenderer;
import org.jfree.chart.renderer.category.LineAndShapeRenderer;
import org.jfree.data.category.DefaultCategoryDataset;
import org.jfree.ui.RectangleEdge;

public class FileUtil {
	private FileUtil() {

	}

	public static void main(String args[]) {

		/*
		 * OutputStream op = new FileOutputStream("J:\\学生表New.xlsx");
		 * sxssfWorkbook.write(op); op.close();
		 * 
		 * System.out.println(sxssfWorkbook.getSheetAt(0).getRow(1).getCell(0));
		 * System.out.println(sxssfWorkbook.getSheetAt(0).getRow(1).getCell(1));
		 * System.out.println(sxssfWorkbook.getSheetAt(0).getRow(1).getCell(2));
		 */
		try {
			XSSFWorkbook wb = new XSSFWorkbook(new FileInputStream("D:\\test.xlsx"));
			SXSSFWorkbook sxssfWorkbook = new SXSSFWorkbook(wb, -1);

			// 第一步，创建一个webbook，对应一个Excel文件
			// SXSSFWorkbook wb = new SXSSFWorkbook();
			// 第二步，在webbook中添加一个sheet，对应Excel文件中的 sheet
			SXSSFSheet sheet = (SXSSFSheet) sxssfWorkbook.createSheet();
			// 设置具体数据
			List<Object[]> list = new ArrayList<Object[]>();
			Object[] obj1 = { 111, 112, 113 };
			Object[] obj2 = { 221, 222, 223 };
			Object[] obj3 = { 331, 332, 333 };
			list.add(obj1);
			list.add(obj2);
			list.add(obj3);

			File file = FileUtil.createChartLine(list, "title图", "X轴", "Y轴", "567");
			// FileUtil.imageOut(wb, sheet, file);

			File file2 = FileUtil.createChartBar(list, "title图", "X轴", "Y轴", "567");
			// FileUtil.imageOut(wb, sheet, file2);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static File createChartLine(List<Object[]> list, String title, String xTitle, String yTitle, String num) {
		// public static void main(String args[]){
		// 构造数据集合
		DefaultCategoryDataset dataset = new DefaultCategoryDataset();
		for (int i = 0; list != null && i < list.size(); i++) {
			Object[] obj = list.get(i);
			dataset.addValue(Integer.parseInt(obj[0].toString()), "数据", obj[1].toString() + "\n" + obj[2].toString());
		}

		// 核心对象
		JFreeChart chart = ChartFactory.createLineChart(title, // 图形的主标题
				xTitle, // X轴外标签的名称
				yTitle, // Y轴外标签的名称
				dataset, PlotOrientation.VERTICAL, // 图形的显示方式（水平和垂直）
				true, // 是否显示子标题
				true, // 是否在图形上显示数值的提示
				true); // 是否生成URL地址
		// 解决主标题的乱码
		chart.getTitle().setFont(new Font("宋体", Font.BOLD, 18));
		// 解决子标题的乱码
		chart.getLegend().setItemFont(new Font("宋体", Font.BOLD, 15));
		chart.getLegend().setPosition(RectangleEdge.RIGHT);// 右侧显示子菜单
		// 获取图表区域对象
		CategoryPlot categoryPlot = (CategoryPlot) chart.getPlot();
//			categoryPlot.setBackgroundPaint(null);
		// 获取X轴对象
		CategoryAxis categoryAxis = (CategoryAxis) categoryPlot.getDomainAxis();
		// 获取Y轴对象
		NumberAxis numberAxis = (NumberAxis) categoryPlot.getRangeAxis();
		// 解决X轴上的乱码
		categoryAxis.setTickLabelFont(new Font("宋体", Font.BOLD, 15));
		// 解决X轴外的乱码
		categoryAxis.setLabelFont(new Font("宋体", Font.BOLD, 15));
		// 解决Y轴上的乱码
		numberAxis.setTickLabelFont(new Font("宋体", Font.BOLD, 15));
		// 解决Y轴外的乱码
		numberAxis.setLabelFont(new Font("宋体", Font.BOLD, 15));

		// 改变Y轴的刻度，默认值从1计算
		numberAxis.setAutoTickUnitSelection(false);
		NumberTickUnit unit = new NumberTickUnit(Integer.parseInt(num));
		numberAxis.setTickUnit(unit);

		// 获取绘图区域对象
		LineAndShapeRenderer lineAndShapeRenderer = (LineAndShapeRenderer) categoryPlot.getRenderer();
		lineAndShapeRenderer.setBaseShapesVisible(true);// 设置转折点

		// 让数值显示到页面上
		lineAndShapeRenderer.setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator());
		lineAndShapeRenderer.setBaseItemLabelsVisible(true);
		lineAndShapeRenderer.setBaseItemLabelFont(new Font("宋体", Font.BOLD, 15));

		// 显示图形
//			ChartFrame chartFrame = new ChartFrame("xyz", chart);
//			chartFrame.setVisible(true);
//			chartFrame.pack();

		String filename = DateFormatUtils.format(new Date(), "yyyyMMddHHmmss") + ".png";// 用时间作为文件名防止重名的问题发生
		File file = new File(filename);// 保存文件到web容器中
		try {
			ChartUtilities.saveChartAsPNG(file, chart, 600, 500);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return file;
	}

	public static File createChartBar(List<Object[]> list, String title, String xTitle, String yTitle, String num) {

		DefaultCategoryDataset dataset = new DefaultCategoryDataset();
		for (int i = 0; list != null && i < list.size(); i++) {
			Object[] obj = list.get(i);
			dataset.addValue(Integer.parseInt(obj[0].toString()), "数据", obj[1].toString() + "\n" + obj[2].toString());
		}

		JFreeChart chart = ChartFactory.createBarChart(title, // 图表的主标题
				xTitle, // X轴（种类轴）外的标题
				yTitle, // Y轴（值轴）外的标题
				dataset, // 数据的集合
				PlotOrientation.VERTICAL, // 图形的显示形式（水平/垂直）
				true, // 是否生成子标题
				true, // 是否生成提示的工具
				true); // 是否在图像上生成URL路径

		// 处理乱码
		// 处理主标题乱码
		chart.getTitle().setFont(new Font("宋体", Font.BOLD, 18));
		// 处理子标题乱码
		chart.getLegend().setItemFont(new Font("宋体", Font.BOLD, 15));
		chart.getLegend().setPosition(RectangleEdge.RIGHT);// 右侧显示子菜单
		// 调出图表区域对象
		CategoryPlot categoryPlot = (CategoryPlot) chart.getPlot();
		// 获取到X轴
		CategoryAxis categoryAxis = (CategoryAxis) categoryPlot.getDomainAxis();
		// 获取到Y轴
		NumberAxis numberAxis = (NumberAxis) categoryPlot.getRangeAxis();
		// 处理X轴外的乱码
		categoryAxis.setLabelFont(new Font("宋体", Font.BOLD, 15));
		// 处理X轴上的乱码
		categoryAxis.setTickLabelFont(new Font("宋体", Font.BOLD, 15));
		// 处理Y轴外的乱码
		numberAxis.setLabelFont(new Font("宋体", Font.BOLD, 15));
		// 处理Y轴上的乱码
		numberAxis.setTickLabelFont(new Font("宋体", Font.BOLD, 15));

		// 处理Y轴上的刻度，默认从1开始
		numberAxis.setAutoTickUnitSelection(false);
		NumberTickUnit unit = new NumberTickUnit(Integer.parseInt(num));
		numberAxis.setTickUnit(unit);

		// 处理图形，先要获取绘图区域对象
		BarRenderer barRenderer = (BarRenderer) categoryPlot.getRenderer();
		// 设置图形的宽度
//		barRenderer.setMaximumBarWidth(0.1);

		// 在图形上显示对应数值
		barRenderer.setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator());
		barRenderer.setBaseItemLabelsVisible(true);
		barRenderer.setBaseItemLabelFont(new Font("宋体", Font.BOLD, 15));

		String filename = DateFormatUtils.format(new Date(), "yyyyMMddHHmmss") + ".png";
		File file = new File(filename);
		try {
			ChartUtilities.saveChartAsPNG(file, chart, 600, 500);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return file;
	}

	private static void imageOut(SXSSFWorkbook wb, SXSSFSheet sheet, File file) {
		ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();
		BufferedImage bufferImg;
		try {
			bufferImg = ImageIO.read(file);
			ImageIO.write(bufferImg, "png", byteArrayOut);
			Drawing dp = sheet.createDrawingPatriarch();
			XSSFClientAnchor anchor = new XSSFClientAnchor(0, 0, 512, 255, 7, 4, 10, 20);// 设置图表在excel中位置
			anchor.setAnchorType(2);
			dp.createPicture(anchor, wb.addPicture(byteArrayOut.toByteArray(), wb.PICTURE_TYPE_PNG)).resize(0.8);
		} catch (IOException e) {
			e.printStackTrace();
		}

	}
}
